package com.goa.task;

import com.goa.cache.SessionMap;
import com.goa.config.SemaphoreManager;
import com.goa.core.SessionTrackingHandler;
import com.goa.entity.DeviceBase;
import com.goa.entity.DeviceCron;
import com.goa.parse.ModbusCRC16;
import com.goa.utils.BeanUtils;
import com.goa.utils.MapUtils;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DynamicJob implements Job {

    private static SessionTrackingHandler sendTcpCommod = BeanUtils.getBean(SessionTrackingHandler.class);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap dataMap = context.getJobDetail().getJobDataMap();
        DeviceCron jobEntity = parseJobDataMap(dataMap);
        log.info("执行当前定时任务{}",jobEntity);
        String sendAddressIp = jobEntity.getAddressIp();
        Channel channel=null;
        String deviceId = jobEntity.getDeviceId();//设备Id
        Map<DeviceBase, Channel> reverseMap = MapUtils.reverseMap(SessionMap.deviceMap);
        Set<DeviceBase> deviceBases = reverseMap.keySet();
        DeviceBase device =null; //当前设备对象
        for (DeviceBase deviceBase : deviceBases) {
            Integer id = deviceBase.getId();
            if (deviceId.equals(id.toString())){
                channel = reverseMap.get(deviceBase);
            }
        }

        if (channel!=null){
            //TODO 此处数据库添加设备编号
            String crc16 = ModbusCRC16.getCRC16("01" + jobEntity.getCommandCode());
            String code ="01"+jobEntity.getCommandCode()+crc16;
            try {
                boolean flag = SemaphoreManager.tryAcquireSemaphore(channel, 30, TimeUnit.SECONDS);
                log.info("上锁的设备IP是{},====上锁是否成功{}",channel.remoteAddress(),flag);
            } catch (InterruptedException e) {
                log.error("获取锁时发生异常: {}", e.getMessage());
                Thread.currentThread().interrupt(); // 恢复中断状态
            }
            log.info("给设备"+sendAddressIp+"====发送的指令是"+jobEntity.getAddressIp()+jobEntity.getCommandCode()+crc16);
            //0104000000067008
            sendTcpCommod.sendCommandToClient(channel,code,jobEntity);
        }else {
            log.info(sendAddressIp+"未获取到连接对象");
        }

    }

    public static DeviceCron parseJobDataMap(JobDataMap dataMap) {
        DeviceCron jobEntity = new DeviceCron();
        jobEntity.setId(dataMap.getInt("id"));
        jobEntity.setJobName(dataMap.getString("jobName"));
        jobEntity.setCronExpression(dataMap.getString("cronExpression"));
        jobEntity.setDescription(dataMap.getString("description"));
        jobEntity.setCommandName(dataMap.getString("commandName"));
        jobEntity.setAddressIp(dataMap.getString("addressIp"));
        jobEntity.setCommandCode(dataMap.getString("commandCode"));
        jobEntity.setDeviceId(dataMap.getString("deviceId"));
        jobEntity.setAddressIp(dataMap.getString("addressIp"));
        jobEntity.setMappingId(dataMap.getInt("mappingId"));
        return jobEntity;
    }
}
